package com.zenithmind.task.controller;

import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import com.zenithmind.task.pojo.entity.TaskAttachment;
import com.zenithmind.task.pojo.query.TaskAttachmentQuery;
import com.zenithmind.task.pojo.vo.TaskAttachmentVO;
import com.zenithmind.task.service.TaskAttachmentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 任务附件管理控制器
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/zenithMind/task-attachment")
@RequiredArgsConstructor
@Tag(name = "任务附件管理", description = "任务附件的上传、下载、删除等功能")
public class TaskAttachmentController {

    private final TaskAttachmentService taskAttachmentService;

    // ==================== 基础CRUD操作 ====================

    @GetMapping("/page")
    @Operation(summary = "分页查询任务附件列表", description = "支持多条件筛选的任务附件分页查询")
    public Result<PageResult<TaskAttachmentVO>> getTaskAttachmentPage(TaskAttachmentQuery query) {
        String userId = UserContext.requireUserId();
        PageResult<TaskAttachmentVO> result = taskAttachmentService.getTaskAttachmentPage(query, userId);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "查询任务附件详情", description = "根据ID查询任务附件的详细信息")
    public Result<TaskAttachmentVO> getTaskAttachmentById(@Parameter(description = "附件ID") @PathVariable String id) {
        String userId = UserContext.requireUserId();
        TaskAttachmentVO taskAttachment = taskAttachmentService.getTaskAttachmentById(id, userId);
        return Result.success(taskAttachment);
    }

    @PostMapping
    @Operation(summary = "创建任务附件", description = "创建新的任务附件记录")
    public Result<Boolean> createTaskAttachment(@Valid @RequestBody TaskAttachment taskAttachment) {
        String userId = UserContext.requireUserId();
        Boolean result = taskAttachmentService.createTaskAttachment(taskAttachment, userId);
        return Result.success(result);
    }

    @PutMapping
    @Operation(summary = "更新任务附件", description = "更新任务附件信息")
    public Result<Boolean> updateTaskAttachment(@Valid @RequestBody TaskAttachment taskAttachment) {
        String userId = UserContext.requireUserId();
        Boolean result = taskAttachmentService.updateTaskAttachment(taskAttachment, userId);
        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除任务附件", description = "删除指定的任务附件")
    public Result<Boolean> deleteTaskAttachment(@Parameter(description = "附件ID") @PathVariable String id) {
        String userId = UserContext.requireUserId();
        Boolean result = taskAttachmentService.deleteTaskAttachment(id, userId);
        return Result.success(result);
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除任务附件", description = "批量删除多个任务附件")
    public Result<Boolean> batchDeleteTaskAttachments(@RequestBody List<String> ids) {
        String userId = UserContext.requireUserId();
        Boolean result = taskAttachmentService.batchDeleteTaskAttachments(ids, userId);
        return Result.success(result);
    }

    // ==================== 文件操作 ====================

    @PostMapping("/upload")
    @Operation(summary = "上传任务附件", description = "上传文件作为任务附件")
    public Result<TaskAttachmentVO> uploadTaskAttachment(
            @Parameter(description = "任务ID") @RequestParam String taskId,
            @Parameter(description = "上传文件") @RequestParam("file") MultipartFile file,
            @Parameter(description = "附件描述") @RequestParam(required = false) String description) {
        String userId = UserContext.requireUserId();
        TaskAttachmentVO result = taskAttachmentService.uploadTaskAttachment(taskId, file, description, userId);
        return Result.success(result);
    }

    @PostMapping("/upload/batch")
    @Operation(summary = "批量上传任务附件", description = "批量上传多个文件作为任务附件")
    public Result<List<TaskAttachmentVO>> batchUploadTaskAttachments(
            @Parameter(description = "任务ID") @RequestParam String taskId,
            @Parameter(description = "上传文件列表") @RequestParam("files") MultipartFile[] files,
            @Parameter(description = "附件描述") @RequestParam(required = false) String description) {
        String userId = UserContext.requireUserId();
        List<TaskAttachmentVO> result = taskAttachmentService.batchUploadTaskAttachments(taskId, files, description, userId);
        return Result.success(result);
    }

    @GetMapping("/{id}/download")
    @Operation(summary = "下载任务附件", description = "下载指定的任务附件文件")
    public void downloadTaskAttachment(
            @Parameter(description = "附件ID") @PathVariable String id,
            jakarta.servlet.http.HttpServletResponse response) {
        String userId = UserContext.requireUserId();
        taskAttachmentService.downloadTaskAttachment(id, userId, response);
    }

    @GetMapping("/{id}/preview")
    @Operation(summary = "预览任务附件", description = "预览指定的任务附件（支持图片、文档等）")
    public Result<String> previewTaskAttachment(@Parameter(description = "附件ID") @PathVariable String id) {
        String userId = UserContext.requireUserId();
        String previewUrl = taskAttachmentService.getAttachmentPreviewUrl(id, userId);
        return Result.success(previewUrl);
    }

    // ==================== 查询方法 ====================

    @GetMapping("/task/{taskId}")
    @Operation(summary = "查询任务的附件列表", description = "查询指定任务的所有附件")
    public Result<List<TaskAttachmentVO>> getTaskAttachments(
            @Parameter(description = "任务ID") @PathVariable String taskId) {
        String userId = UserContext.requireUserId();
        List<TaskAttachmentVO> result = taskAttachmentService.getTaskAttachments(taskId, userId);
        return Result.success(result);
    }

    @GetMapping("/my")
    @Operation(summary = "查询我上传的附件", description = "查询当前用户上传的所有任务附件")
    public Result<PageResult<TaskAttachmentVO>> getMyTaskAttachments(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        String userId = UserContext.requireUserId();
        PageResult<TaskAttachmentVO> result = taskAttachmentService.getUserTaskAttachments(userId, pageNum, pageSize);
        return Result.success(result);
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取附件统计信息", description = "获取任务附件的统计信息")
    public Result<Object> getAttachmentStatistics(
            @Parameter(description = "任务ID") @RequestParam(required = false) String taskId) {
        String userId = UserContext.requireUserId();
        Object result = taskAttachmentService.getAttachmentStatistics(taskId, userId);
        return Result.success(result);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索任务附件", description = "根据关键词搜索任务附件")
    public Result<List<TaskAttachmentVO>> searchTaskAttachments(
            @Parameter(description = "搜索关键词") @RequestParam String keyword,
            @Parameter(description = "文件类型") @RequestParam(required = false) String fileType) {
        String userId = UserContext.requireUserId();
        List<TaskAttachmentVO> result = taskAttachmentService.searchTaskAttachments(keyword, fileType, userId);
        return Result.success(result);
    }
}
